package com.tgy.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: tgy
 * @Date: 12/20/20 3:24 PM
 *
 * https://leetcode-cn.com/problems/permutations-ii/
 */
public class _47_全排列_II {

    public List<List<Integer>> permuteUnique(int[] nums) {

        List<List<Integer>> rets = new ArrayList<>();

        if (nums == null || nums.length == 0) {

            return rets;
        }

        search(nums,0,rets);
        return rets;
    }

    private void search(int[] nums, int level, List<List<Integer>> rets) {


        if (level == nums.length) {

            rets.add(Arrays.stream(nums).boxed().collect(Collectors.toList()));
            return;
        }

        for (int i = level; i < nums.length; i++) {

            if (isJump(nums,level,i)) {

                continue;
            }

            swap(nums,level,i);
            search(nums,level+1,rets);
            swap(nums,level,i);
        }

    }

    private void swap(int[] nums, int i1, int i2) {

        if (i1 == i2) {

            return;
        }

        int tmp = nums[i1];
        nums[i1] = nums[i2];
        nums[i2] = tmp;
    }

    private boolean isJump(int[] nums,int start, int index) {

        for (int i = start; i < index; i++) {

            if (nums[i] == nums[index]) {

                return true;
            }

        }

        return false;
    }
}
